package sample;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ViewWaveServlet extends HttpServlet {
  @SuppressWarnings("unchecked")
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String waveId = request.getParameter("waveId");
    if(waveId == null || waveId.equals("")) {
      throw new ServletException("Wave ID not specified");
    }
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    String blipQuery = "select from " + BlipRecord.class.getName() + " where waveId == '" + waveId + "'";
    List<BlipRecord> blipRecords = (List<BlipRecord>) pm.newQuery(blipQuery).execute();
    if(blipRecords.size() == 0) {
      throw new ServletException("No blips found for this Wave ID");
    }
    
    String waveQuery = "select from " + WaveletRecord.class.getName() + " where waveId == '" + waveId + "'";;
    List<WaveletRecord> waveletRecords = (List<WaveletRecord>) pm.newQuery(waveQuery).execute();
    if(waveletRecords.size() == 0) {
      throw new ServletException("No waves found for this Wave ID");
    }
    WaveletRecord waveletRecord = waveletRecords.get(0);
    pm.close();
    
    request.setAttribute("waveletRecord", waveletRecord);
    request.setAttribute("blipRecords", blipRecords);
    request.getRequestDispatcher("viewWave.jsp").forward(request, response);
  }
}
